package com.example.emos.wx.checkin.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.example.emos.wx.core.common.util.R;
import com.example.emos.wx.core.config.SystemConstants;
import com.example.emos.wx.checkin.model.form.CheckinForm;
import com.example.emos.wx.checkin.model.form.SearchMonthCheckinForm;
import com.example.emos.wx.core.exception.EmosException;
import com.example.emos.wx.checkin.service.CheckinService;
import com.example.emos.wx.user.service.UserService;
import com.example.emos.wx.user.shiro.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/8/7
 */
@Slf4j
@RestController
@RequestMapping("/checkin")
@Api("签到")
public class CheckinController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CheckinService checkinService;
    @Value("${emos.image-folder}")
    private String imageFolder;
    @Autowired
    private UserService userService;
    @Autowired
    private SystemConstants constants;

    @GetMapping("/validCanCheckIn")
    @ApiOperation("查看用户今天是否可以签到")
    public R validCanCheckIn(@RequestHeader("token")String token){
        int userId = jwtUtil.getUserIdFromJwt(token);
        String result = checkinService.validCanCheckIn(userId, DateUtil.today());
        return R.ok(result);
    }
    @PostMapping("/checkin")
    @ApiOperation("签到")
    public R checkin(@Valid CheckinForm form, @RequestParam("photo") MultipartFile file,@RequestHeader("token")String token)  {
//        判断上传的文件是不是空的
        if(file==null){
            return R.error("没有上传文件");
        }
//        从token中解析得到对应的userId
        int userId = jwtUtil.getUserIdFromJwt(token);
//        获取文件的后缀名并且全部小写比如.jpg.png等
        String fileName = file.getOriginalFilename().toLowerCase();
//        判断上传的文件是不是.jpg的文件
        if(!fileName.endsWith(".jpg")) {
            return R.error("必须提交JPG格式图片");
        }else {
//            定义保存该.jpg文件的路径
            String path = imageFolder+"/"+fileName;
            System.out.println("checkin:"+path);
            try{
//                将文件保存在路径path中
                file.transferTo(Paths.get(path));
//                封装相关的参数
                HashMap map = new HashMap();
                map.put("userId",userId);
                map.put("path",path);
                map.put("city",form.getCity());
                map.put("district",form.getDistrict());
                map.put("address",form.getAddress());
                map.put("country",form.getCountry());
                map.put("province",form.getProvince());
//                实现签到
                checkinService.checkin(map);
                return R.ok("签到成功");
            }catch (IOException e){
                log.error(e.getMessage(),e);
                throw new EmosException("图片保存错误");
            }finally {
//                签到完成之后删除文件
                FileUtil.del(path);
            }
        }
    }
    @PostMapping("/createFaceModel")
    @ApiOperation("创建人脸模型")
    public R createFaceModel(@RequestParam("photo")MultipartFile file,@RequestHeader("token")String token){
        int userId = jwtUtil.getUserIdFromJwt(token);
        if(file == null){
            return R.error("没有上传文件");
        }
        String fileName = file.getOriginalFilename().toLowerCase();
        String path = imageFolder+"/"+fileName;
        System.out.println("createFaceModel:"+path);
        if(!fileName.endsWith(".jpg")){
            return R.error("必须提交JPG格式的图片");
        }else {
            try {
                file.transferTo(Paths.get(path));
                checkinService.createFaceModel(userId,path);
                return R.ok("创建成功");
            }catch (IOException e){
                log.error(e.getMessage());
                throw new EmosException("保存图片错误");
            }
        }
    }
    @GetMapping("/searchTodayCheckin")
    @ApiOperation("查询用户当日前签到数据")
    public R searchTodayCheckin(@RequestHeader("token") String token){
        int userId = jwtUtil.getUserIdFromJwt(token);
        HashMap map = checkinService.searchTodayCheckin(userId);
        System.out.println("map:"+map);
        map.put("attendanceStartTime",constants.attendanceStartTime);
        map.put("closingTime",constants.closingTime);
        long days = checkinService.searchCheckinDays(userId);
        map.put("checkinDays",days);
        DateTime hiredDate = DateUtil.parse(userService.searchUserHiredate(userId));
        DateTime startDate = DateUtil.beginOfWeek(DateUtil.date());
        if(startDate.isBefore(hiredDate)){
            startDate=hiredDate;
        }
        DateTime endDate = DateUtil.endOfWeek(DateUtil.date());
        HashMap param = new HashMap();
        param.put("startDate",startDate.toString());
        param.put("endDate",endDate.toString());
        param.put("userId",userId);
        ArrayList<HashMap> list = checkinService.searchWeekCheckin(param);
        map.put("weekCheckin",list);
        return R.ok().put("result",map);
    }
    @PostMapping("/searchMonthCheckin")
    @ApiOperation("查询用户某月签到数据")
    public R searchMonthCheckin(@Valid @RequestBody SearchMonthCheckinForm form,@RequestHeader("token") String token){
//        获取用户的id
        int userId =jwtUtil.getUserIdFromJwt(token);
//        根据用户id查询用户的入职日期
        userService.searchUserHiredate(userId);
//        获取该用户的入职日期
        DateTime hiredate = DateUtil.parse(userService.searchUserHiredate(userId));
//        如果月份小于10比如9变为09
        String month = form.getMonth()<10?"0"+form.getMonth():form.getMonth().toString();
//        获取当年当月的开始日期比如2023-08-01
        DateTime startDate = DateUtil.parse(form.getYear()+"-"+month+"-01");
//        入职日期的当年当月的开始日期在当年当月的开始日期之前的日期，比如当年当月的开始日期是2023-08-01，入职日期是2023-06-25，那么入职日期的开始日期是2023-06-01
        if(startDate.isBefore(DateUtil.beginOfMonth(hiredate))){
            throw new EmosException("只能查询考勤之后日期的数据");
        }
//        当年当月的开始日期在入职日期之前那么就将其改为入职日期的日子
        if(startDate.isBefore(hiredate)){
            startDate = hiredate;
        }
        DateTime endDate = DateUtil.endOfMonth(startDate);
        HashMap map = new HashMap();
        map.put("userId",userId);
        map.put("startDate",startDate.toString());
        map.put("endDate",endDate.toString());
        //获取当月的信息
        ArrayList<HashMap> list = checkinService.searchMonthCheckin(map);
        int sum_1=0,sum_2=0,sum_3=0;
        for (HashMap<String,String> one:list){
//            判断当前是休息日还是工作日
            String type = one.get("type");
            String status = one.get("status");
            if("工作日".equals(type)){
                if ("正常".equals(status)){
                    sum_1++;
                }else if("迟到".equals(status)){
                    sum_2++;
                }else if ("缺勤".equals(status)){
                    sum_3++;
                }
            }
        }
        return R.ok().put("list",list).put("sum_1",sum_1).put("sum_2",sum_2).put("sum_3",sum_3);
    }
}
